package org.wsocket.socketset;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.wsocket.Exception.WSocketException;
import org.wsocket.thread.HandShakeMessageTask;
import org.wsocket.thread.ThreadPool;

public class SocketSetManager extends Thread {

	private static Logger log=Logger.getLogger(SocketSetManager.class);
	private Selector selector = null;

	public SocketSetManager(int[] ports) {
		try {
			selector = Selector.open();
			for(int i = 0; i < ports.length; i++){
				InetSocketAddress isa = new InetSocketAddress(ports[i]);
				ServerSocketChannel server = ServerSocketChannel.open();
				server.socket().bind(isa);
				server.configureBlocking(false);
				server.register(selector, SelectionKey.OP_ACCEPT,server);
			}
		} catch (IOException e) {
			log.error(e);
		}
	}

	public void run() {
		try {
			while (selector.select() > 0) {
				Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); 
			    while(keyIter.hasNext()) { 
			        SelectionKey sk = keyIter.next(); 
			        keyIter.remove(); 
					if (sk.isAcceptable()) {
						SocketChannel sc = ((ServerSocketChannel)sk.attachment()).accept();
						sc.socket().setSoTimeout(5000);
						HandShakeMessageTask hsTask = new HandShakeMessageTask(sc);
						ThreadPool.assginGenerateTask(hsTask);
						sk.interestOps(SelectionKey.OP_ACCEPT);
					}
				}
			}
		} catch (IOException e) {
			log.error(e);
		} catch (WSocketException e) {
			log.error(e);
		}
	}
}
